#include <string.h>
#include <ncurses.h>
#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>

void draw_menu(char *options[], int current_hightlight, int start_row)
{
	int current_row = 0;
	char  **option_ptr;
	char *txt_ptr;

	attrset(COLOR_PAIR(3));
	option_ptr = options;
	while (*option_ptr) {
		if (current_row == current_hightlight)
			attron(A_STANDOUT);
		txt_ptr = options[current_row];
		mvprintw(start_row + current_row, COLS / 2 - strlen(txt_ptr) / 2, "%s", txt_ptr);
		if (current_row == current_hightlight)
			attroff(A_STANDOUT);

		current_row++;
		option_ptr++;
	}

	refresh();
}

int get_choise(char *choises[])
{
	static int selected_row = 0;
	int max_row = 0;
	int start_screenrow = 6;
	char **option;
	int selected;
	int key = 0;

	option = choises;
	while (*option) {
		max_row++;
		option++;
	}

	if (selected_row >= max_row)
		selected_row = 0;

	clear_all_screen();
	keypad(stdscr, TRUE);
	cbreak();
	noecho();
	key = 0;

	while (key != 'q' && key != KEY_ENTER && key != '\n') {
		if (key == KEY_UP) {
			if (selected_row == 0)
				selected_row = max_row - 1;
			else
				selected_row--;
		}

		if (key == KEY_DOWN) {
			if (selected_row == (max_row - 1))
				selected_row = 0;
			else
				selected_row++;
		}

		selected = *choises[selected_row];
		draw_menu(choises, selected_row, start_screenrow);
		key = getch();
	}
	keypad(stdscr, FALSE);
	nocbreak();
	echo();

	if (key == 'q')
		selected = 'q';
	return(selected);
}

void clear_all_screen()
{
	clear();
	char *copy_txt = "Copyright (c) 2012, by Alexey Myachin.";
  char *title_txt = "Time life.";
  int cx = (COLS / 2) - (strlen(copy_txt) / 2);
  int cy = LINES - 2;
  int tx = (COLS / 2) - (strlen(title_txt) / 2);
  int ty = 3;

  attrset(COLOR_PAIR(1));
  mvprintw(cy, cx, "%s", copy_txt);
  attrset(COLOR_PAIR(2));
  mvprintw(ty, tx, "%s", title_txt);
  refresh();
  sleep(3);
}